import $ from 'jquery'
import { FETCH_QUESTIONS, FETCH_QUESTION_LIST, RESTORE_QUESTION_LIST, INIT_ALL_OPTION_CACHE, OPTION_SELECTED } from '../constants/actionTypes'

function setLoadingState(type) {
    return {
        type,
        loading: true
    }
}

function receiveList(type, status, data, error = '') {
    return {
        type,
        status,
        data,
        error
    }
}

function restoreList(obj) {
    let mObj = {type: RESTORE_QUESTION_LIST};
    return Object.assign(mObj, obj);
}

// 初始化选项缓存
function initOptionCache(type, len) {
    let i = 0,
        data = [];
    for(i; i<len; i++) {
         data.push(null);
    }
    return {
        type,
        data
    }
}

export function requestTestGroupListData() {
    return dispatch => {
        dispatch(setLoadingState(FETCH_QUESTION_LIST));
        $.ajax({
            url: 'data/page_list.json',
            type: 'GET',
            dataType: 'JSON',
            success: function (resp) {
                dispatch(receiveList(FETCH_QUESTION_LIST, true, resp));
            },
            error: function() {
                dispatch(receiveList(FETCH_QUESTION_LIST, false, '', '网络不可用'));
            }
        })
    }
}

export function requestQuestionsData(qid) {
    return dispatch => {
        dispatch(setLoadingState(FETCH_QUESTIONS));
        $.ajax({
            url: 'data/'+qid+'.json',
            type: 'GET',
            dataType: 'JSON',
            success: function (resp) {
                dispatch(receiveList(FETCH_QUESTIONS, true, resp));
                let len = resp.data && resp.data.length ? resp.data.length : 0;
                dispatch(initOptionCache(INIT_ALL_OPTION_CACHE, len));
            },
            error: function() {
                dispatch(receiveList(FETCH_QUESTIONS, false, '', '网络不可用'));
            }
        })
    }
}

export function restoreQuestionsData(data) {
    return dispatch => {
        dispatch(restoreList(data));
    }
}

export function optionSelected(data, index, selectedItem, questionType, score) {
    return dispatch => {
        dispatch({
            type: OPTION_SELECTED,
            data,
            index,
            selectedItem,
            questionType,
            score
        });
    }
}
